﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.Linq;
using Designit.Umb.Newsletter.Bll;
using umbraco.BasePages;
using umbraco.DataLayer;

namespace Designit.Umb.Newsletter.Custom.plugins.designit.newsletter
{
    public partial class testMil : UmbracoEnsuredPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                XmlDocument doc = new XmlDocument();
            string path = @"/config/designit/newsletter/mailSettings.config";
            path = Server.MapPath(path);
            doc.Load(path);
            XmlNode xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='TestMail']");
            txtModtager.Text = xnode.Attributes[1].Value;
            }
            

        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            int id = Int32.Parse(Request["id"]);
            string cont = EmbedNewsletter.EmbSend(id);

            using (var reader =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsLetterCampaignNewsletter where id=@id",
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id)))
            {
                while (reader.Read())
                {
                    //replace @companyname
                    string regex = "@CompanyName";
                    string replacement = reader.GetString("campfrom");
                    cont = Regex.Replace(cont, regex, replacement, RegexOptions.IgnoreCase);

                    //replace @companymail
                    regex = "@CompanyMail";
                    replacement = reader.GetString("campreplyMail");
                    cont = Regex.Replace(cont, regex, replacement, RegexOptions.IgnoreCase);

                    //replace href local tags 
                    regex = @"href=""(.*?)""";

                    foreach (var match in Regex.Matches(cont, regex, RegexOptions.IgnoreCase))
                    {
                        string url = match.ToString().Substring(6, match.ToString().Length - 7);
                        if (url.StartsWith("/{localLink"))
                        {


                            url = umbraco.library.NiceUrl(Int32.Parse(url.Substring(12, url.Length - 13)));
                            string regexLocal = @"href=""http://" + Request.ServerVariables.Get("HTTP_HOST") + url +
                                                @"""";
                            cont = Regex.Replace(cont, match.ToString(), regexLocal, RegexOptions.IgnoreCase);
                        }


                    }


                    XmlDocument doc = new XmlDocument();
                    string path = @"/config/designit/newsletter/mailSettings.config";
                    path = Server.MapPath(path);
                    doc.Load(path);
                    XmlNode xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Mail']");
                    string fromMail = xnode.Attributes[1].Value;
                    xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Smtp']");
                    string smtp = xnode.Attributes[1].Value;
                    xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpPort']");
                    string smtpPort = xnode.Attributes[1].Value;
                    xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='SmtpAuth']");
                    string smtpAuth = xnode.Attributes[1].Value;




                    SmtpClient cl = new SmtpClient(smtp, Int32.Parse(smtpPort));

                    if (smtpAuth == "true")
                    {
                        xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='UserId']");
                        string userId = xnode.Attributes[1].Value;
                        xnode = doc.SelectSingleNode("//mailSettings/mailSetting[@name='Password']");
                        string password = xnode.Attributes[1].Value;
                        cl.Credentials = new NetworkCredential(userId, password);
                    }
                    string[] lines = Regex.Split(txtModtager.Text, ",|;");
                    foreach (string s in lines)
                    {
                        MailMessage testMail = new MailMessage(fromMail, s);

                        testMail.Subject = reader.GetString("campsubject");

                        // SEND IN HTML FORMAT (comment this line to send plain text).
                        testMail.IsBodyHtml = true;

                        // HTML Body (remove HTML tags for plain text).
                        testMail.Body = cont;
                        cl.Send(testMail);
                    }


                }
            }
            StringBuilder sb =new StringBuilder();
            sb.AppendLine(@"<script type=""text/javascript"">");
            sb.AppendLine("top.closeModal();");
            sb.AppendLine("</script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "close", sb.ToString());
            speechBubble(BasePage.speechBubbleIcon.success, "Test mail sent","");
        }
    }
}
